class ReservationsController < ApplicationController
  layout 'reservations'
  
  before_filter :check_logged_in, :only => [:new, :edit, :update, :destroy]
  # GET /reservations
  # GET /reservations.xml
  
  
  def index
    @reservation = Reservation.new
    
  end
  
  
  # GET /reservations/1
  # GET /reservations/1.xml
  def show
    @reservation = Reservation.find(:all)
    
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @reservation }
    end
  end

  # GET /reservations/new
  # GET /reservations/new.xml
  def new
    @reservation = Reservation.new
    

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @reservation }
    end
  end

  # GET /reservations/1/edit
  def edit
    @reservation = Reservation.find(params[:id])
  end
  

  # POST /reservations
  # POST /reservations.xml
  def create
    @reservation = Reservation.new(params[:reservation])
    
    respond_to do |format|
      if @reservation.save
        after_create
        
        flash[:notice] = 'Reservation was successfully created.'
        format.html { redirect_to(@reservation) }
        format.xml  { render :xml => @reservation, :status => :created, :location => @reservation }
        
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @reservation.errors, :status => :unprocessable_entity }
      end
    end
  end
    
    def after_create
      @reservations = Reservation.find(:all)
      @dernier_objet = @reservations[-1]
      @chambre = Chambre.find(@dernier_objet.chambre_id)
      @change = @chambre.update_attribute(:status, "Occupée")
      
    end

  # PUT /reservations/1
  # PUT /reservations/1.xml
  def update
    @reservation = Reservation.find(params[:id])

    respond_to do |format|
      if @reservation.update_attributes(params[:reservation])
        flash[:notice] = 'Reservation was successfully updated.'
        format.html { redirect_to(@reservation) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @reservation.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /reservations/1
  # DELETE /reservations/1.xml
  def destroy
    @reservation = Reservation.find(params[:id])
    @reservation.destroy

    respond_to do |format|
      format.html { redirect_to(reservations_url) }
      format.xml  { head :ok }
    end
  end

  
  private 
    def check_logged_in
      authenticate_or_request_with_http_basic("Welcome to Admin Pages") do |username, password|
        username == "victor" && password == "victor"
      end
    end
  
end
